package com.shoppingmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.shoppingmall.common.ServletResponse;
import com.shoppingmall.dao.CategoryMapper;
import com.shoppingmall.dao.ProductMapper;
import com.shoppingmall.pojo.Category;
import com.shoppingmall.pojo.Product;
import com.shoppingmall.service.ProductService;
import com.shoppingmall.vo.ProductDetailVo;
import com.shoppingmall.vo.ProductListVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by
 *
 * @author touni
 * @date 2019/3/19
 * @time 18:06
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     *
     * 1 上架true   0 下架 false
     *
     * service私有的获取商品状态的方法
     * @return
     */
    private boolean getProductStatus(Integer productId){
        //查询数据库获取状态
        Product productFormQuery = productMapper.selectByPrimaryKey(productId);
        if (null == productFormQuery){
            return false;
        }
        if (productFormQuery.getStatus() == 1){
            return true;
        }
        return false;

    }

    @Override
    public ServletResponse getProductDetail(Integer productId) {

        ProductDetailVo productDetailVo = productMapper.selectProductDetailByProductId(productId);
        //补全vo的属性 imageHost   parentCategoryId   todo 待补全imageHost
        // todo  category_id 无法自动装配 此逻辑无法走通
        //Category category = categoryMapper.selectByPrimaryKey(productDetailVo.getCategoryId());
        //productDetailVo.setParentCategoryId(category.getParentId());



        return ServletResponse.createBySuccess(productDetailVo);
    }

    @Override
    public ServletResponse listAllProduct(Integer pageNum, Integer pageSize) {
        //设置分页
        PageHelper.startPage(pageNum,pageSize);
        //执行查询逻辑  这里执行自动装配到vo中，其中imagehost属性需要单独设置
        List<ProductListVo> allProductList = productMapper.selectAllProduct();
        //  todo imageHost属性需要单独设置

        PageInfo pageInfo = new PageInfo(allProductList);

        return ServletResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServletResponse listProductByProductNameOrProductId(String productName, Integer productId, Integer pageNum, Integer pageSize) {
        //设置分页
        PageHelper.startPage(pageNum,pageSize);
        //拼接需要查询的productname
        productName = new StringBuilder().append("%").append(productName).append("%").toString();

        //执行查询逻辑  todo imagehost需要设置 指的是图片主机的前缀  可以直接在vo中设置
        List<ProductListVo> productListVoList =  productMapper.selectProductByProductNameOrProductId(productName,productId);
        PageInfo pageInfo = new PageInfo(productListVoList);

        return ServletResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServletResponse setSaleStatus(Integer productId, Integer status) {
        //首先根据ID查询这个商品
        Product productFormQuery = productMapper.selectByPrimaryKey(productId);
        if (null == productFormQuery){
            return ServletResponse.createByErrorMessage("商品不存在！！！");
        }
        if (productFormQuery.getStatus() == status){
            return ServletResponse.createByErrorMessage("状态相同不需要修改");
        }
        productFormQuery.setStatus(status);
        //执行更新
        int flag = productMapper.updateByPrimaryKey(productFormQuery);
        if (1 != flag){
            return ServletResponse.createByErrorMessage("更新状态失败");
        }



        return ServletResponse.createBySuccess("更新状态成功");
    }

    @Override
    public ServletResponse saveOrUpdate(Product product) {
        //判断是修改还是新增
        if (null == product.getId()){
            //新增
            int flag = productMapper.insert(product);
            if (1 !=flag){
                return ServletResponse.createByErrorMessage("新增商品失败");
            }
            return ServletResponse.createBySuccess("新增商品成功");

        }
        //需要根据传入的id查询是否有这个商品，如没有商品直接返回无此商品
        Product productFromQuery = productMapper.selectByPrimaryKey(product.getId());
        if (null == productFromQuery){
            return ServletResponse.createByErrorMessage("无此商品修改失败");
        }

        int flag = productMapper.updateByPrimaryKey(product);
        if (1 !=flag){
            return ServletResponse.createByErrorMessage("修改商品失败");
        }
        return ServletResponse.createBySuccess("修改商品成功");
    }

    /**
     * 使用用户前台查询，只能查询到已上架的商品    传入的是分类的ID ，需要查看这个分类下是否有子分类的ID
     * SQL语句验证status是否等于1
     * 如果没有category和keyword 默认查询全部  判空在SQL中处理
     * sql入参为list和 String keyword
     * @param categoryId
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @param orderBy
     * @return
     */
    @Override
    public ServletResponse userListProductByCategoryIdAndKeyword(Integer categoryId, String keyword, Integer pageNum, Integer pageSize, String orderBy) {

        ArrayList<Integer> categoryIdList = Lists.newArrayList();
        //判断category是否为空
        if (null != categoryId){
            //父节点不为空时 注意加上父节点
            categoryIdList.add(categoryId);
            //查询是否有子节点
            List<Category> sonCategories = categoryMapper.selectCategoryByParentId(categoryId);
            if (CollectionUtils.isNotEmpty(sonCategories)) {
                for (Category category : sonCategories) {
                    categoryIdList.add(category.getId());
                }
            }
        }
        // tip pagehelper有多条语句的时候需要放在要设置的语句前面
        //设置分页
        PageHelper.startPage(pageNum,pageSize);
        //设置排序
        if (StringUtils.isNotBlank(orderBy)) {
            String[] strings = orderBy.trim().split("_");
            PageHelper.orderBy(strings[0] + " " + strings[1]);
        }
        // 封装keyword
        if (StringUtils.isNotBlank(keyword)) {
            keyword = new StringBuilder().append("%").append(keyword.trim()).append("%").toString();
        }

        //传入的集合可能为空  需要在SQL中判空
        List<ProductListVo> productListVo = productMapper.selectStatusProduct(categoryIdList,keyword);
        //封装查询结果
        PageInfo pageInfo = new PageInfo(productListVo);
        return ServletResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServletResponse userGetProductDetail(Integer productId) {
        ProductDetailVo productDetailVo = productMapper.selectUserProductDetail(productId);






        return ServletResponse.createBySuccess(productDetailVo);
    }
}
